from machine import Pin
import time
import tm1637

# 数码管控制对象
tm = tm1637.TM1637(clk=Pin(23), dio=Pin(22))

# LED 控制对象
led = Pin(16, Pin.OUT)

# 按键控制对象
key_start = Pin(12, Pin.IN, Pin.PULL_UP)  # K1 开始
key_stop = Pin(14, Pin.IN, Pin.PULL_UP)   # K2 停止

# 按键防抖处理
def debounce(pin):
    time.sleep_ms(20)
    return pin.value() == 0

# 倒计时总秒数（600秒 = 10分钟）
total_seconds = 10
running = False  # 是否正在运行
last_tick = time.ticks_ms()

# 显示函数：格式 MMSS
def display_time(seconds):
    minutes = seconds // 60
    secs = seconds % 60
    tm.show("{:02d}{:02d}".format(minutes, secs))

# 主循环
if __name__ == "__main__":
    display_time(total_seconds)
    while True:
        # 检测开始键
        if debounce(key_start) and not running:
            running = True
            last_tick = time.ticks_ms()
            while key_start.value() == 0:
                pass  # 等待释放按键

        # 检测停止键
        if debounce(key_stop) and running:
            running = False
            while key_stop.value() == 0:
                pass  # 等待释放按键

        # 如果处于运行状态，处理倒计时
        if running and total_seconds > 0:
            current = time.ticks_ms()
            if time.ticks_diff(current, last_tick) >= 1000:
                total_seconds -= 1
                last_tick = current
                display_time(total_seconds)

        # 倒计时为 0 时，LED 闪烁
        if total_seconds == 0:
            led.value(1)
            time.sleep(0.5)
            led.value(0)
            time.sleep(0.5)
        else:
            led.value(0)  # 非倒计时结束状态，LED保持关闭
